package web.commons;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.wicket.markup.html.form.IChoiceRenderer;

/**
 * Simple property-based ChoiceRenderer.
 * Use the given property names as the source to obtain the
 * respective ID and LABEL strings used to render the Choice
 * to the Hosting component.
 * <p/>
 * Example:
 * <p/>
 * //somewhere, in SomePersistentData.java file...
 * public class SomePersistentData implements Serializable {
 * private Integer id;
 * private String  description;
 * //plus, getters and setters....
 * }
 * <p/>
 * //extract Objects from DB
 * List values = myService.findDataElements();
 * <p/>
 * add( new DropDownChoice( "myWicketId",
 * new PropertyModel(myDataObject, "propertyName" ),
 * values,
 * new PropertyChoiceRenderer( "id", "description" ) ))
 *
 * @author Davide Alberto Molin (davide.molin@gmail.com)
 */
public class PropertyChoiceRenderer<T> implements IChoiceRenderer<T> {

    //name of the property used to extract the ID for the choice option
    private String idProperty;
    //name of the property used to extract the LABEL for the choice option
    private String valueProperty;

    public PropertyChoiceRenderer(String idProperty, String valueProperty) {
        this.idProperty = idProperty;
        this.valueProperty = valueProperty;
    }

    public Object getDisplayValue(T object) {
        return getPropertyValue(object, valueProperty);
    }

    public String getIdValue(T object, int index) {
        return getPropertyValue(object, idProperty).toString();
    }

    private Object getPropertyValue(T object, String property) {
        try {
            return BeanUtils.getProperty(object, property);
        }
        catch (Exception err) {
            //in case of exception, fall back to simple toString...
            return object.toString();
        }
    }


}